"""日志记录工具"""

import logging
import sys
from pathlib import Path
from typing import Optional
from datetime import datetime
from logging.handlers import RotatingFileHandler


class Logger:
    """自定义日志记录器"""
    
    def __init__(self, name: str = "file_organizer", 
                 log_dir: Optional[Path] = None,
                 level: int = logging.INFO):
        """初始化日志记录器"""
        self.name = name
        self.level = level
        
        if log_dir is None:
            self.log_dir = Path.home() / ".file_organizer" / "logs"
        else:
            self.log_dir = Path(log_dir)
        
        self.log_dir.mkdir(parents=True, exist_ok=True)
        self._setup_logger()
    
    def _setup_logger(self) -> None:
        """设置日志记录器"""
        self.logger = logging.getLogger(self.name)
        self.logger.setLevel(self.level)
        
        # 清除现有处理器
        self.logger.handlers.clear()
        
        # 创建格式器
        formatter = logging.Formatter(
            fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        # 控制台处理器
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)
        
        # 文件处理器 - 主日志
        main_log_file = self.log_dir / "app.log"
        file_handler = RotatingFileHandler(
            main_log_file,
            maxBytes=10*1024*1024,  # 10MB
            backupCount=5,
            encoding='utf-8'
        )
        file_handler.setLevel(self.level)
        file_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)
        
        # 错误日志文件处理器
        error_log_file = self.log_dir / "error.log"
        error_handler = RotatingFileHandler(
            error_log_file,
            maxBytes=5*1024*1024,  # 5MB
            backupCount=3,
            encoding='utf-8'
        )
        error_handler.setLevel(logging.ERROR)
        error_handler.setFormatter(formatter)
        self.logger.addHandler(error_handler)
    
    def debug(self, message: str, **kwargs) -> None:
        """记录调试信息"""
        self.logger.debug(self._format_message(message, kwargs))
    
    def info(self, message: str, **kwargs) -> None:
        """记录信息"""
        self.logger.info(self._format_message(message, kwargs))
    
    def warning(self, message: str, **kwargs) -> None:
        """记录警告"""
        self.logger.warning(self._format_message(message, kwargs))
    
    def error(self, message: str, **kwargs) -> None:
        """记录错误"""
        self.logger.error(self._format_message(message, kwargs))
    
    def critical(self, message: str, **kwargs) -> None:
        """记录严重错误"""
        self.logger.critical(self._format_message(message, kwargs))
    
    def exception(self, message: str, **kwargs) -> None:
        """记录异常"""
        self.logger.exception(self._format_message(message, kwargs))
    
    def _format_message(self, message: str, kwargs: dict) -> str:
        """格式化日志消息"""
        if kwargs:
            # 添加额外信息
            extra_info = " | ".join([f"{k}={v}" for k, v in kwargs.items()])
            return f"{message} | {extra_info}"
        return message
    
    def log_operation(self, operation: str, file_path: str, 
                     result: str, **kwargs) -> None:
        """记录文件操作"""
        self.info(
            f"文件操作",
            operation=operation,
            file_path=file_path,
            result=result,
            **kwargs
        )
    
    def log_llm_request(self, provider: str, model: str, 
                       prompt_length: int, response_time: float,
                       success: bool, **kwargs) -> None:
        """记录LLM请求"""
        level = self.info if success else self.error
        level(
            f"LLM请求",
            provider=provider,
            model=model,
            prompt_length=prompt_length,
            response_time=f"{response_time:.2f}s",
            success=success,
            **kwargs
        )
    
    def log_workspace_operation(self, workspace_id: str, operation: str,
                              result: str, **kwargs) -> None:
        """记录工作空间操作"""
        self.info(
            f"工作空间操作",
            workspace_id=workspace_id,
            operation=operation,
            result=result,
            **kwargs
        )
    
    def set_level(self, level: int) -> None:
        """设置日志级别"""
        self.level = level
        self.logger.setLevel(level)
        for handler in self.logger.handlers:
            if isinstance(handler, logging.StreamHandler):
                handler.setLevel(level)


# 全局日志记录器实例
_global_logger: Optional[Logger] = None


def get_logger(name: str = "file_organizer") -> Logger:
    """获取全局日志记录器"""
    global _global_logger
    if _global_logger is None:
        _global_logger = Logger(name)
    return _global_logger


def setup_logging(log_dir: Optional[Path] = None, level: int = logging.INFO) -> Logger:
    """设置日志系统"""
    global _global_logger
    _global_logger = Logger(log_dir=log_dir, level=level)
    return _global_logger